"use client";

import React, { createContext, useContext, useState, ReactNode, useEffect, useCallback } from 'react';
import Cookies from 'js-cookie';
import { User } from "@/types";

interface AuthContextType {
  isAuthenticated: boolean;
  user: User | null;
  login: (token: string) => Promise<void>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

async function fetchWithAuth(url: string, options: RequestInit = {}) {
  const token = Cookies.get('token');
  const headers = {
    ...options.headers,
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  };
  const response = await fetch(url, { ...options, headers });
  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.message || '请求失败');
  }
  return response.json();
}

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<User | null>(null);

  const logout = useCallback(async () => {
    try {
      await fetchWithAuth('http://localhost:8080/login/logout', { method: 'GET' });
    } catch (error) {
      console.error('登出失败:', error);
    } finally {
      Cookies.remove('token');
      setUser(null);
      setIsAuthenticated(false);
    }
  }, []);

  const getLoginUser = useCallback(async () => {
    try {
      const data = await fetchWithAuth('http://localhost:8080/login/getLoginUser');
      if (data.success) {
        setUser(data.data);
        setIsAuthenticated(true);
      } else {
        throw new Error(data.message || '获取用户信息失败');
      }
    } catch (error) {
      console.error(error);
      await logout();
    }
  }, [logout]);

  useEffect(() => {
    const token = Cookies.get('token');
    if (token) {
      getLoginUser();
    }
  }, [getLoginUser]);

  const login = async (_token: string) => {
    await getLoginUser();
  };



  return (
    <AuthContext.Provider value={{ isAuthenticated, user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};